package com.hxd.otc.module.wallet.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.module.wallet.contract.AddWalletContactContract;
import com.hxd.otc.module.wallet.presenter.AddWalletContactPresenter;
import com.hxd.otc.other.CustomBounceTopEnter;
import com.hxd.otc.other.OnPermissionsResult;
import com.hxd.otc.other.SlideTopExit;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.BlocksToast;
import com.hxd.otc.widget.TitleBar;
import com.hxd.otc.widget.TypeWindow;
import com.hxd.otc.widget.WalletDialogTipsUtil;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by lzy on 2018/8/6 0006.
 * description ${添加钱包联系人}
 */
public class AddWalletContactActivity extends PermissionActivity<AddWalletContactPresenter> implements AddWalletContactContract.View {
    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.et_name)
    EditText mEtName;
    @BindView(R.id.tv_currency)
    TextView mTvCurrency;
    @BindView(R.id.et_wallet_address)
    EditText mEtWalletAddress;
    @BindView(R.id.iv_scan_qr_code)
    ImageView mIvScanQrCode;

    private String[] PERMISSION = {Manifest.permission.CAMERA};
    public static final int REQUEST_CODE_PERMISSION = 111;

    private TypeWindow mTypeWindow;

    String coinParameters[];

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_wallet_contact;
    }

    @Override
    protected AddWalletContactPresenter createPresenter() {
        return new AddWalletContactPresenter(this);
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {
        mPresenter.getCoinType();
    }

    @Override
    protected void initEvent() {
        mTitleBar.setOnTitleBarItemClickListener(new TitleBar.OnTitleBarItemClickListener() {
            @Override
            public void onBack(View v) {

            }

            @Override
            public void onRight(View v) {
                onComplete();
            }
        });
    }

    private void onComplete() {
        String name = mEtName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            BlocksToast.get().showToast(R.string.wallet_toast_add_contacts_name_empty);
            return;
        }

        String coin = mTvCurrency.getText().toString().trim();
        if (!TextUtils.isEmpty(coin) && coin.equals(getString(R.string.wallet_add_contacts_coin_select))) {
            BlocksToast.get().showToast(R.string.wallet_toast_add_contacts_coin_empty);
            return;
        }

        String address = mEtWalletAddress.getText().toString().trim();
        if (TextUtils.isEmpty(address)) {
            BlocksToast.get().showToast(R.string.wallet_toast_add_contacts_address_empty);
            return;
        }

        mPresenter.addWalletContact(coinMap.get(coin), coin, address, name);
    }

    @OnClick({R.id.iv_scan_qr_code, R.id.tv_currency})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_scan_qr_code:
                requestPermission();
                break;
            case R.id.tv_currency:
                if (coinParameters == null || coinParameters.length <= 0) {
                    return;
                }
                showSelectType();
                break;
        }
    }

    private void requestPermission() {
        super.requestPermission(new OnPermissionsResult() {
            @Override
            public void onAllow(List<String> allowPermissions) {
                if (PERMISSION.length == allowPermissions.size()) {
                    $startActivityForResult(CommonCaptureActivity.class, REQUEST_CODE_PERMISSION);
                }
            }

            @Override
            public void onNoAllow(List<String> noAllowPermissions) {
                WalletDialogTipsUtil.showCameraTipsDialog(AddWalletContactActivity.this);
            }

            @Override
            public void onForbid(List<String> noForbidPermissions) {
                WalletDialogTipsUtil.showCameraTipsDialog(AddWalletContactActivity.this);
            }

            @Override
            public void onLowVersion() {
                $startActivityForResult(CommonCaptureActivity.class, REQUEST_CODE_PERMISSION);
            }
        }, PERMISSION);
    }

    private void showSelectType() {
        mTypeWindow = new TypeWindow(this, coinParameters, getString(R.string.wallet_add_contacts_coin_select), mTvCurrency.getWidth());
        mTypeWindow.setOnItemClickListener(new TypeWindow.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mTypeWindow.superDismiss();
                mTvCurrency.setText(coinParameters[position]);
            }
        });
        mTypeWindow.offset(0, 0)
                .anchorView(mTvCurrency)
                .gravity(Gravity.BOTTOM)
                .showAnim(new CustomBounceTopEnter())
                .dismissAnim(new SlideTopExit())
                .dimEnabled(false)
                .show();

        mTvCurrency.setCompoundDrawables(null, null, ResourceUtil.getDrawable(R.mipmap.wallet_up_menu_icon), null);

        mTypeWindow.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mTvCurrency.setCompoundDrawables(null, null, ResourceUtil.getDrawable(R.mipmap.wallet_down_menu_icon), null);
            }
        });
    }

    @Override
    public void addWalletContractSuccess() {
        showToast(getString(R.string.wallet_add_contacts_success));
        setResult(RESULT_OK);
        finish();
    }

    Map<String, String> coinMap;
    List<String> coinList;

    @Override
    public void coinTypeSuccess() {
        coinMap = new HashMap<>();
        coinList = new ArrayList<>();

        for (int i = 0; i < mPresenter.getWalletInfoBeans().size(); i++) {
            if (mPresenter.getWalletInfoBeans().get(i).tokenStatus == 1
                    || mPresenter.getWalletInfoBeans().get(i).tokenStatus == 3) {
                coinMap.put(mPresenter.getWalletInfoBeans().get(i).getName(),
                        mPresenter.getWalletInfoBeans().get(i).getId());
                coinList.add(mPresenter.getWalletInfoBeans().get(i).getName());
                continue;
            }

        }
        coinParameters = new String[coinList.size()];


        for (int i = 0; i < coinList.size(); i++) {
            coinParameters[i] = coinList.get(i);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE_PERMISSION) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    mEtWalletAddress.setText(result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    BlocksToast.get().showToast(R.string.wallet_toast_scan_code_re_fail);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UIUtils.dismissDialog(mTypeWindow);
    }
}
